package core;

import database.CommentDb;
import database.CourseDb;
import database.TakeCourseDb;
import database.UserDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jimmyhsu on 2016/12/16.
 */
public class StudentSelectCourse extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String courseIdStr = StringUtils.getUtf8String(req.getParameter("courseId"));
        String studentId = StringUtils.getUtf8String(req.getParameter("studentId"));
        String type = StringUtils.getUtf8String(req.getParameter("type"));
        resp.setContentType("text/html;charset=utf-8");
        if (StringUtils.isAnyoneEmpty(courseIdStr, studentId, type)) {
            resp.getWriter().print("<script>alert('操作失败！传参异常');location.href='../Student/selectCourse.jsp'</script>");
        } else {
            int courseId = Integer.parseInt(courseIdStr);
            if (type.equals("select")) {
                if (CourseDb.getStudentNumberInCourse(courseId) >= CourseDb.selectCourseById(courseId).getMaxNumber()) {
                    resp.getWriter().print("<script>alert('选课失败-人数已满');location.href='../Student/selectCourse.jsp';</script>");
                } else {
                    CommentDb.deleteQuitReason(studentId, courseId);
                    TakeCourseDb.addCourseForStudent(studentId, courseId);
                    resp.getWriter().print("<script>alert('选课成功');location.href='../Student/selectCourse.jsp';</script>");
                }
            } else if (type.equals("quit")) {
                String reason = StringUtils.getUtf8String(req.getParameter("quitReason"));
                TakeCourseDb.removeStudentFromCourse(studentId, courseId);
                CommentDb.insertQuitReason(studentId, courseId, reason);
                resp.getWriter().print("<script>alert('退课成功');location.href='../Student/selectCourse.jsp';</script>");
            } else {
                resp.getWriter().print("<script>alert('非法操作！');location.href='../Student/selectCourse.jsp';</script>");
            }
        }
    }
}
